<?php
/**
 * Created by PhpStorm.
 * User: songdewei
 * Date: 2017/10/10
 * Time: 下午2:09
 */

namespace App\WeChat\WxApi;

use GuzzleHttp\Client;
use Illuminate\Support\Facades\Cache;

class WxApi
{
    public $appid = '';
    public $appsecret = '';

    /**
     * WxApi constructor.
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    function __construct()
    {
        $this->appid = setting('wx_appid');
        $this->secret = setting('wx_secret');
    }

    /**
     * @return bool
     * @throws \Exception
     */
    public static function getAccessToken(){
        $cache = Cache::remember('weixinAccessToken', 100, function (){
            $api = new static();
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$api->appid."&secret=".$api->secret;

            $client = new Client();
            $response = $client->get($url);
            if ($response->getStatusCode() == 200) {
                $data = json_decode($response->getBody(), true);
                if (isset($data['access_token'])) {
                    return $data;
                }
            }
            return ['access_token'=>''];
        });
        return $cache['access_token'];
    }

    /**
     * @return bool
     * @throws \Exception
     */
    public static function getJsApiTicket(){
        $cache = Cache::remember('weixinJsapiTicket', 100, function (){
            $uri  = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=".WxApi::getAccessToken();

            $client = new Client();
            $response = $client->get($uri);
            if ($response->getStatusCode() == 200) {
                $data = json_decode($response->getBody(), true);
                if (isset($data['ticket'])){
                    return $data;
                }
            }
            return ['ticket'=>''];
        });
        return $cache['ticket'];
    }
}
